package com.common.transparent.module;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.support.v4.content.PermissionChecker.checkSelfPermission;

/**
 * Created : wen
 * DateTime : 2017/9/27 00:14
 * Description :
 */
public class PermissionManager {

    public static boolean checkPermission(Context context, String permissions) {
        boolean result;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getTargetSdkVersion(context) >= Build.VERSION_CODES.M) {
                result = context.checkSelfPermission(permissions) == PERMISSION_GRANTED;
            } else {
                result = checkSelfPermission(context, permissions) == PERMISSION_GRANTED;
            }
        } else {
            result = true;
        }
        return result;
    }

    private static int getTargetSdkVersion(Context context) {
        int targetSdkVersion = 0;
        try {
            final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return targetSdkVersion;
    }

}
